package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.adapter.MyLoveStoryAdapter;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.model.StudentDeviceModel;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.util.CommonUtil;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.IntentConstants;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.widget.PopDeleteWindow;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;

//import com.jdy.haoduoaiteacher.R;


/**
 * 我的消息
 *
 * @author Administrator
 *
 */
public class PublishPhotoActivity extends BaseActivity implements OnClickListener{

  @InjectView(id = R.id.content_views)
  private ListView listview_devices;

  @InjectView(id = R.id.img_ablum, click=true)
  private ImageView img_ablum;
  @InjectView(id = R.id.tittle_back_btn2222, click=true)
  private ImageView tittle_back_btn2222;

  @InjectView(id = R.id.img_camera, click=true)
  private ImageView img_camera;

  private MyLoveStoryAdapter mStoryAdapter;

  public ArrayList<StudentDeviceModel> mStudentDeviceModelList;

  private LeUser mLeUser;

  private int mSelPosition = 0;

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mymessage_teacher);

    hideTitleView();

    tittle_back_btn2222 = (ImageView) findViewById(R.id.tittle_back_btn2222);
    tittle_back_btn2222.setClickable(true);
    mLeUser = MyTeacherApp.getInstance().getUserTeacher();
    getBindDevices();

    img_camera.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    img_ablum.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

    listview_devices.setOnItemClickListener(new AdapterView.OnItemClickListener(){
      @Override
      public void onItemClick(AdapterView<?> parent, View view,
                              int position, long id) {
        mStoryAdapter.setHighLightPosition(position);
        mSelPosition = position;
      }
    });

    listview_devices.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
      @Override
      public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

        PopDeleteWindow popWindow = new PopDeleteWindow(PublishPhotoActivity.this);
        //产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);

        mSelPosition = position;

        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
          @Override
          public void onDismiss() {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = 1f;
            getWindow().setAttributes(lp);
          }
        });

        popWindow.setOnMenuClickListener(new PopDeleteWindow.OnMenuClickListener() {
          @Override
          public void onClickShare() {
// 拍照
            takePhoto();
          }

          @Override
          public void onClickDelete() {


// 相册选择
            Intent intent = new Intent(PublishPhotoActivity.this,
                    ImageBucketChooseActivity.class);
            intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, 9);
            intent.putExtra("classFrom", PublishPhotoActivity.class.toString());
            intent.putExtra("macid", mStudentDeviceModelList.get(mSelPosition).machine_id);
            startActivity(intent);


          }

          @Override
          public void onClickCancel() {
// TODO
          }
        });

        if (!popWindow.isShowing()) {
          int[] location = new int[2];
          view.getLocationOnScreen(location);

          int xoff = popWindow.getWidth()/2-view.getWidth()/2;
          popWindow.update();
          popWindow.showAsDropDown(view, -xoff, -view.getHeight()/2);

        } else {
          popWindow.dismiss();
        }

        return true;
      }
    });
  }

  private void getBindDevices() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity,
                                ResponseResult result) {
        if (result.isSuccess()) {
          if (Tools.isNotNullStr(result.data)) {
            try {
              JSONArray array = new JSONArray(result.data);

              mStudentDeviceModelList = (ArrayList<StudentDeviceModel>) JsonSerializer
                      .getInstance().deserialize(array.toString(),
                              ArrayList.class, StudentDeviceModel.class);

            } catch (Exception e) {

            }

            if (mStudentDeviceModelList!=null && !mStudentDeviceModelList.isEmpty()) {
              mStoryAdapter = new MyLoveStoryAdapter(PublishPhotoActivity.this, mStudentDeviceModelList);
              mStoryAdapter.setPublishPhoto(true);
              listview_devices.setAdapter(mStoryAdapter);
              Tools.setListViewHeightBasedOnChildren(listview_devices);
              //  mStoryAdapter.notifyDataSetChanged();
              mStoryAdapter.setHighLightPosition(mSelPosition);
            }
          }
        } else {
          if (Tools.isNotNullStr(result.data)) {
            Toast.makeText(PublishPhotoActivity.this, result.data,
                    Toast.LENGTH_SHORT).show();
          }
        }
        // }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        Log.e("SNO222222",mLeUser.sno );
        return HttpUtils.startRequest(HttpUtils.HOST_API
                        + "/api/2.0/teacher/teacher_machine", param_,
                HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private static final File PHOTO_DIR = new File(
          Environment.getExternalStorageDirectory() + "/CameraCache");
  private File mCurrentPhotoFile;// 照相机拍照得到的图片
  private File mCacheFile;
  private  String fileName;

  private  final int CAMERA_WITH_DATA = 1002;// 相机

  /**
   * 拍照
   */
  private void takePhoto() {
          String status = Environment.getExternalStorageState();
      if (status.equals(Environment.MEDIA_MOUNTED)) {
        if (!PHOTO_DIR.exists()) {
          PHOTO_DIR.mkdirs();// 创建照片的存储目录
        }
        fileName = System.currentTimeMillis() + ".jpg";
        mCurrentPhotoFile = new File(PHOTO_DIR, fileName);
        Intent intentC = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        if (Build.VERSION.SDK_INT >= 24) {
          Uri imageUri = FileProvider.getUriForFile(this,
                  "com.goldmedalnewconcept.fileprovider", mCurrentPhotoFile);
          intentC.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
          intentC.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        } else {
          intentC.putExtra(MediaStore.EXTRA_OUTPUT,
                  Uri.fromFile(mCurrentPhotoFile));
        }
        startActivityForResult(intentC, CAMERA_WITH_DATA);
      } else {
        toastShow("没有SD卡");
      }
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.tittle_back_btn2222:
      this.finish();
        break;

    case R.id.img_ablum:
      Intent intent = new Intent(PublishPhotoActivity.this,
              MyLoveListActivity.class);

      intent.putExtra("studentmodel", mStudentDeviceModelList.get(mSelPosition));

      intent.putExtra("isphoto", true);

      startActivity(intent);
      break;
    case R.id.img_camera:
      if (mStoryAdapter!= null && mStoryAdapter.getSelectView() != null) {
        PopDeleteWindow popWindow = new PopDeleteWindow(PublishPhotoActivity.this);
        //产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);

        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
          @Override
          public void onDismiss() {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = 1f;
            getWindow().setAttributes(lp);
          }
        });

        popWindow.setOnMenuClickListener(new PopDeleteWindow.OnMenuClickListener() {
          @Override
          public void onClickShare() {
            // 拍照
            takePhoto();
          }

          @Override
          public void onClickDelete() {


            // 相册选择

            Intent intent = new Intent(PublishPhotoActivity.this,
                    ImageBucketChooseActivity.class);
            intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, 9);
            intent.putExtra("macid", mStudentDeviceModelList.get(mSelPosition).machine_id);
            intent.putExtra("classFrom", PublishPhotoActivity.class.toString());
           // intent.putExtra("classFrom", AddHabitClockActivity.class.toString());
            startActivity(intent);


          }

          @Override
          public void onClickCancel() {
// TODO
          }
        });
        // popWindow.showPopupWindow(view);


        if (!popWindow.isShowing()) {

          int[] location = new int[2];
          mStoryAdapter.getSelectView().getLocationOnScreen(location);

          //   popWindow.showAtLocation(view, Gravity.CENTER|Gravity.BOTTOM, location[0], 0);

          // popWindow.showAsDropDown(view, view.getLayoutParams().width / 2, 5);

          // 以下拉方式显示popupwindow
          // popWindow.showAsDropDown(view, view.getLayoutParams().width / 2, 5);

          int xoff = popWindow.getWidth()/2-mStoryAdapter.getSelectView().getWidth()/2;
          popWindow.update();
          popWindow.showAsDropDown(mStoryAdapter.getSelectView(), -xoff, -mStoryAdapter.getSelectView().getHeight()/2);

          // popWindow.showAsDropDown(view, view.getLayoutParams().width / 2, 5);
        } else {
          popWindow.dismiss();
        }
      }




//      String status = Environment.getExternalStorageState();
//      if (status.equals(Environment.MEDIA_MOUNTED)) {
//        if (!PHOTO_DIR.exists()) {
//          PHOTO_DIR.mkdirs();// 创建照片的存储目录
//        }
//        fileName = System.currentTimeMillis() + ".jpg";
//        mCurrentPhotoFile = new File(PHOTO_DIR, fileName);
//        Intent intentC = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
//        if (Build.VERSION.SDK_INT >= 24) {
//          Uri imageUri = FileProvider.getUriForFile(this,
//                  "com.haoduoaiteacher.fileprovider", mCurrentPhotoFile);
//          intentC.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//          intentC.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//
//        } else {
//          intentC.putExtra(MediaStore.EXTRA_OUTPUT,
//                  Uri.fromFile(mCurrentPhotoFile));
//        }
//        startActivityForResult(intentC, CAMERA_WITH_DATA);
//      } else {
//        toastShow("没有SD卡");
//      }

      break;
    default:
      break;
    }
  }


  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_CANCELED) {
      return;
    }
    switch (requestCode) {
      case CAMERA_WITH_DATA:// 相册返回
        if (mCurrentPhotoFile == null || !mCurrentPhotoFile.exists()) {
          mCurrentPhotoFile = new File(PHOTO_DIR, fileName);
        }


        uploadImageFile(mCurrentPhotoFile.getAbsolutePath());

        File file = new File(mCurrentPhotoFile.getAbsolutePath());
        try {
          MediaStore.Images.Media.insertImage(getContentResolver(),
                  mCurrentPhotoFile.getAbsolutePath(), "rtm.jpeg", null);
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        }

        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        sendBroadcast(intent);

        break;
    }
  }

  private String imgUrl_toSubmit;

  private void publishImage() {
    showloading("");
    new CustomAsyncTask(PublishPhotoActivity.this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          toastShow("照片发布成功!");
        } else {
          dismissLoading();
          toastShow(result.data);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        if (mLeUser == null) {
          mLeUser = MyTeacherApp.getInstance().getUserTeacher();
        }
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put("macid", mStudentDeviceModelList.get(mSelPosition).machine_id);
        param_.put("url", imgUrl_toSubmit);
        return HttpUtils.startRequest(HttpUtils.HOST_API
                        + "/api/2.0/teacher/teacher_photo", param_,
                HttpUtils.TAG_POST_REQUEST);

      }
    }).execute("请检查网络连接!");
  }

  private void uploadImageFile(final String filePath) {
 //   showloading("");
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          imgUrl_toSubmit = result.data;
          if (Tools.isNotEmpty(imgUrl_toSubmit)) {
            publishImage();
          }
        } else {

          toastShow(result.data);
        }

        dismissLoading();
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        if (mLeUser == null) {
          mLeUser = MyTeacherApp.getInstance().getUserTeacher();
        }
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_MODULE_I, "teacher/photo");
        return HttpUtils.startUploadRequest(HttpUtils.API_URL
                        + HttpUtils.UPLOAD_BABY_AVATAR_POST, param_, "Filedata", filePath,
                HttpUtils.TAG_POST_REQUEST);

      }
    }).execute("请检查网络连接!");
  }

  @Override
  protected void onResume() {

//    if (adapter != null) {
//      adapter.notifyDataSetChanged();
//    }

    super.onResume();
  }
}
